package com.example.controller;

import com.example.entity.MyResponseEntity;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author fyx
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public MyResponseEntity<String> uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        // 判断是否上传文件
        if (file.isEmpty()) {
            return MyResponseEntity.creat(400, "请求错误", "请上传文件");
        }
        //上传文件的路径
        String realPath = request.getServletContext().getRealPath("/images/");
        //上传的文件名
        String fileName = file.getOriginalFilename();
        // 确定保存路径
        File realFile = new File(realPath, fileName);
        // 判断父级文件夹是否存在
        if (!realFile.getParentFile().exists()) {
            boolean flag = realFile.getParentFile().mkdirs();
            if (!flag) {
                return MyResponseEntity.creat(500, "失败", "新建文件夹失败");
            }
        }
        try {
            // 将文件写入磁盘
            file.transferTo(realFile);
        } catch (IOException e) {
            return MyResponseEntity.creat(500, "失败", "接收文件失败");
        }
        return MyResponseEntity.creat(200, "请求成功", "上传成功");
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> downLoad(HttpServletRequest request, @RequestParam("filename") String fileName) {
        //获取文件的真实路径
        String realPath = request.getServletContext().getRealPath("/images/");
        File realFile = new File(realPath, fileName);
        // 创建下载时发送错误的响应头
        HttpHeaders errorHeader = new HttpHeaders();
        errorHeader.setContentType(MediaType.APPLICATION_JSON);
        // 判断文件是否存在
        if (!realFile.exists()) {
            return new ResponseEntity<>("文件不存在!".getBytes(StandardCharsets.UTF_8), errorHeader, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        // 文件存在，创建正确的响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        //通知浏览器下载方式文件
        httpHeaders.setContentDispositionFormData("attachment",
                new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        // 设置mime类型为application/octet-stream
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            //文件转换为字节数组, 并封装到spring自带的ResponseEntity中
            return new ResponseEntity<>(FileUtils.readFileToByteArray(realFile), httpHeaders, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>("文件名错误!".getBytes(StandardCharsets.UTF_8), errorHeader, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
